# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/6/9'
__author__ = 'Just'
__filename__ = 'user'
"""
from flask import jsonify, g
from app.libs.error_code import ForbiddenException, DeleteSuccess, ParameterException, NotFoundException, Success
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.model.base import db
from app.model.user import User


api = Redprint('user')


@api.route('/<int:uid>', methods=['GET'])
@auth.login_required
def admin_get_user(uid):
    """管理员 获取uid号的用户信息"""
    user = User.query.get_or_404(uid, msg='用户不存在', error_code=6001)
    return jsonify(user)


@api.route('/<int:uid>', methods=['DELETE'])
@auth.login_required
def admin_delete_user(uid):
    """管理员删除某uid账号"""
    mid = g.user.uid
    admin = User.query.get_or_404(mid, msg='用户不存在', error_code=6001)
    user = User.query.filter_by(id=uid).first_or_404(msg='该用户已不存在', error_code=6001)
    if user.auth > admin.auth:
        raise ForbiddenException()
    with db.auto_commit():
        user.delete()
    return DeleteSuccess(msg="删除成功")


@api.route('/<int:uid>/renew', methods=['POST'])
@auth.login_required
def admin_renew_user(uid):
    """管理员恢复某个软删除的客户端账号"""
    mid = g.user.uid
    admin = User.query.get_or_404(mid, msg='用户不存在', error_code=6001)
    user = User.query.get(uid)
    if user.status == 1:
        raise ParameterException(msg='该用户账号状态正常, 无需恢复')
    if not user:
        raise NotFoundException(msg='用户不存在', error_code=6001)
    if user.auth >= admin.auth:
        raise ForbiddenException()
    with db.auto_commit():
        user.status = 1
    return Success(msg="恢复成功")
